package com.totoro.security;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

public class MyAccessDeniedHandler implements AccessDeniedHandler {

	// 请求处理的url
	private String accessDeniedUrl;

	public MyAccessDeniedHandler() {
	}

	public String getAccessDeniedUrl() {
		return accessDeniedUrl;
	}

	public void setAccessDeniedUrl(String accessDeniedUrl) {
		this.accessDeniedUrl = accessDeniedUrl;
	}

	@Override
	public void handle(HttpServletRequest request,
			HttpServletResponse response, AccessDeniedException ex)
			throws IOException, ServletException {
		System.out.println("handle处理了这个界面了吗？？？");
		boolean isAjax = isAjaxRequest(request);
		System.out.println("是否是ajax请求：" + isAjax);
		if (isAjax) {
			request.setAttribute("isAjaxRequest", isAjax);
			request.setAttribute("message", ex.getMessage());
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("/authNotPass.jsp");
			// response.sendRedirect(request.getContextPath() +
			// "/authNotPass.jsp");
			dispatcher.forward(request, response);
		} else {
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ path + "/";
			System.out.println("跳转的页面accessDeniedUrl=  " + accessDeniedUrl);
			response.sendRedirect(basePath + accessDeniedUrl);
		}
	}

	// 判断是否为Ajax请求
	private boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equals(header))
			return true;
		else
			return false;
	}

}
